<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {Course, CourseAssignment, Department} from "../../types";
import {assignCourse, getCourseAssignmentList} from "../../apis/CourseAssignmentApi.ts";
import {ElMessage} from "element-plus";
import {getDepList} from "../../apis/DepartmentApi.ts";
import {getCourseList} from "../../apis/CourseApi.ts";
interface Option {
  key: string
  label: string
  disabled: boolean
}

//穿梭框展示的数据
const data = ref<Option[]>([])
const departmentList = ref<Department[]>()
const courseAssignmentList = ref<CourseAssignment[]>()
const courseList = ref<Course[]>()
//右侧穿梭框数据
const value = ref([])
const selectDepId = ref('')

const getData = async () => {
  const res = await getCourseAssignmentList(selectDepId.value);
  if (res.flag){
    courseAssignmentList.value = res.data

    data.value = []
    value.value = []
    //为data添加数据 查看当前学院下的课程是否选中
    courseList.value?.forEach((course:Course) => {
      //检查data中是否存在该课程 如果有跳过
      if (data.value.find(item => item.key === course.id)){
        return
      }
      data.value.push({
        key: course.id,
        label: course.name,
        disabled: false
      })
      //检查是否选中
      if (courseAssignmentList.value?.find(item => item.courseId === course.id)){
        value.value.push(course.id)
      }
    })
  }else{
    ElMessage.error(res.msg)
  }
}
//获取课程列表
const getCourse = async () => {
  const res = await getCourseList();
  if (res.flag){
    courseList.value = res.data
  }else{
    ElMessage.error(res.msg)
  }
}
const getDepartmentList = async () => {
  const res = await getDepList();
  if (res.flag){
    departmentList.value = res.data
  }
}

const save = async () => {
  if (selectDepId.value === ''){
    ElMessage.info('请选择学院')
    return
  }

  const res = await assignCourse(selectDepId.value,value.value)
  if (res.flag){
    ElMessage.success('保存成功')
  }else{
    ElMessage.error(res.msg)
  }
  await getData(selectDepId.value)

}

//监听下拉列表切换
const selectDepIdChange = async (val:string) => {
    await getData();
}

onMounted(async () => {
  await getDepartmentList()
  await getCourse()
  if (departmentList.value?.length > 0){
    selectDepId.value = departmentList.value[0].id
    await getData(selectDepId.value)
  }
})
</script>

<template>
  <el-row>
    <p style="margin: 10px 25px">选择学院:</p>
    <el-select
        v-model="selectDepId"
        placeholder="Select"
        size="large"
        @change="selectDepIdChange"
        style="width: 240px">
      <el-option
          v-for="item in departmentList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
      />
    </el-select>
  </el-row>
  <br>
  <el-transfer
      :titles="['未分配课程', '已分配课程']"
      :button-texts="['移除', '添加']"
      v-model="value"
      filterable
      filter-placeholder="搜索课程"
      :data="data"
  />
  <br>
  <el-button style="width: 120px;margin:0 245px" type="primary" @click="save">保存</el-button>
</template>

<style scoped>

</style>